<?php


namespace app\index\controller;


use think\Db;

class User extends \Common {

    # 用户登录
    public function Login() {
        if(isset($_POST["phone"]) && isset($_POST["password"])){
            $phone = $_POST["phone"]; $password = $_POST["password"];
            $user = Db::name("users")->where("mobile_phone", $phone)->find();
            if(!empty($user)){
                if($user["password"] == $password){
                    $data = [
                        "token" => $this->BeToken(["uid" => $user["user_id"], "time" => time()])
                    ];
                    $this->Code(200, false, $data);
                }else{
                    $this->Code(403, "密码错误");
                }
            }else{
                $this->Code(403, "用户不存在, 请前去注册");
            }
        }else{
            $this->Code(403, 403);
        }
    }

    # 用户注册
    public function Register(){
        if(isset($_POST["phone"]) && isset($_POST["password"]) && isset($_POST["code"])){
            $phone = $_POST["phone"]; $password = $_POST["password"]; $code = $_POST["code"];
            $check = Db::name("users")->where("mobile_phone", $phone)->find();
            if(empty($check)){
                $checkCode = Db::name("user_tel_code")
                    ->where("is_over", 0)
                    ->where("phone", $phone)
                    ->order("ut_id desc")
                    ->find();
                if(!empty($checkCode)){
                    if($checkCode["code"] == $code){
                        $update = [
                            "is_over" => 1
                        ];
                        $info = [
                            "user_name"    => "U-".$phone,
                            "mobile_phone" => $phone,
                            "password"     => $password
                        ];
                        Db::name("user_tel_code")
                            ->where("phone", $phone)
                            ->update($update);
                        Db::name("users")->insert($info);
                        $this->Code(200, "注册成功, 请前去登录");
                    }else{
                        $this->Code(403, "验证码错误");
                    }
                }else{
                    $this->Code(403, "请点击获取验证码");
                }
            }else{
                $update = [
                    "is_over" => 1
                ];
                $this->Code(403, "手机号已经注册, 请前去登录");
            }
        }else{
            $this->Code(403, 403);
        }
    }

    # 获取用户信息
    public function GetInfo(){

    }

}
